// /**
//  * Created by imouze on 2017-10-26.
//  */

const fs = require('fs');

//
// // 返回path路径下的所有js文件
// const readFile = function (path) {
//     const fs = require('fs');
//     const files = fs.readdirSync('./'+path);
//     const jsFiles = files.filter((f) => {
//         return f.endsWith('.js');
//     });
//     return jsFiles;
// };
//
// // 根据.js文件反射路由
// const SetRouter = function (path) {
//     // 声明路由
//     const router = require('koa-router')();
//
//     const jsFiles = readFile(path);
//     for (const js of jsFiles) {
//         let mapping = require(__dirname + '/' + path + '/' + js); //分别引入每个js文件
//         for (const url in mapping) {
//             // 遍历每个controller文件中的路由
//             if(url.startsWith('Get')) {
//                 // method: get
//                 router.get(url.replace('Get ',''), mapping[url]);
//             } else if (url.startsWith('Post'),mapping[url]) {
//                 // method: post
//                 router.post(url.replace('Post ',''), mapping[url]);
//             } else {
//                 // 非路由的
//                 console.log('this is not router file');
//             }
//         }
//     }
//     return router.routes();
// };
//
// module.exports = function (path) {
//     return SetRouter( path || 'controllers');
// };


function addMapping(router, mapping) {
    for (const url in mapping) {
        if (url.startsWith('GET ')) {
            const path = url.substring(4);
            router.get(path, mapping[url]);
            console.log(`register URL mapping: GET ${path}`);
        } else if (url.startsWith('POST ')) {
            const path = url.substring(5);
            router.post(path, mapping[url]);
            console.log(`register URL mapping: POST ${path}`);
        } else if (url.startsWith('PUT ')) {
            const path = url.substring(4);
            router.put(path, mapping[url]);
            console.log(`register URL mapping: PUT ${path}`);
        } else if (url.startsWith('DELETE ')) {
            const path = url.substring(7);
            router.del(path, mapping[url]);
            console.log(`register URL mapping: DELETE ${path}`);
        } else {
            console.log(`invalid URL: ${url}`);
        }
    }
}

function addControllers(router, dir) {
    fs.readdirSync(__dirname + '/' + dir).filter((f) => {
        return f.endsWith('.js');
    }).forEach((f) => {
        console.log(`process controller: ${f}...`);
        let mapping = require(__dirname + '/' + dir + '/' + f);
        addMapping(router, mapping);
    });
}

module.exports = function (dir) {
    let
        controllers_dir = dir || 'controllers',
        router = require('koa-router')();
    addControllers(router, controllers_dir);
    return router.routes();
};